8
votes

I have done some research on the internet, but I didn't manage to get the complete picture about this subject. Can anyone help to solve this answer for now and forever?

This is what I found so far:

  • It is possible to do cross domain call with jsonp. Altering headers in jsonp call is never allowed
  • It is possible to do cross domain call with json if the server allows it.

This is what I am trying to do :

$.ajax({
    type: "GET",
    crossDomain: true,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization", "Bearer " + ($("#accesstoken").val()));
    },
    contentType: "application/json; charset=utf-8",
    url: myJSonServer + encodeURI(operation),
    dataType: 'json',
    cache: false,
    success: callback,
    error: function (jqXhr, textStatus, errorThrown) { alert(textStatus + ": " + errorThrown); }
});

This is what is happening:

  • When the myJSonServer is on the same domain, there is no problem at all
  • When the myJSonServer is on another domain the request is sent, but without the Bearer header

This Bearer header is part of the oAuth2 standard.

I'm aware of the fact that maybe this is not the best solution, setting the accessToken in the Browser. And I know I could use a proxy for this situation.

I am just curious if it is or will be possible to set the headers on a cross-domain json request?
Thanks

-- Problem solved

I was using MVC4 and added crossDomainScriptAccessEnabled="true" in the web.config. I thought this would be enough, but the answer of apsillers solved my problem. I have now added this in my web.config :

 <system.webServer>
     <httpProtocol>
         <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Authorization" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
3

3 Answers

11
votes

With JSONP, setting custom headers is not possible.

With CORS, the server must send the Access-Control-Allow-Headers header to allow uncommon request headers from the client. From the HTML5 Rocks CORS page:

Access-Control-Allow-Headers ... - Comma-delimited list of the supported request headers.

Thus, your server must send a Access-Control-Allow-Headers: Authorization to let the browser know it is permissible to send Authorization to the server with the request. Without this sever header, the browser will only send a few common headers with the request and ignore the rest.

1
votes

Since "jsonp" works by creating an script tag and using the attribute src= to load resource from another domain. So I don't think there is a way to modify request headers.

0
votes

If you are using JSONP for making cross-origin request - then the answer is no, you can't set HTTP headers on such requests. If you are using CORS for making cross-origin requests - then the answer is yes, since you are using plain XHR to make the request: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing.